package com.kcsj.controller.authority;

import com.alibaba.fastjson.JSONObject;
import com.kcsj.domain.user.User;
import com.kcsj.service.user.UserService;
import com.kcsj.util.MessageHelper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author 傅立贤
 * 25th Nov. 2020
 */
@Slf4j
@WebServlet("/active.ctl")
public class ActiveController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        //获得code
        String code = request.getParameter("code");
        try {
            //验证code是否存在
            User userFindbyCode = UserService.getInstance().findByCode(code);
            //若果对应的user不存在，则结束激活
            if (userFindbyCode==null){
                JSONObject message = MessageHelper.addMessage("激活异常");
                response.getWriter().println(message);
                return;
            }
            //激活
            UserService.getInstance().active(code);
            JSONObject message = MessageHelper.addMessage("激活成功");
            response.getWriter().println(message);
            RequestDispatcher rd=request.getRequestDispatcher("return.jsp");
            rd.forward(request, response);
        }catch (SQLException e){
            JSONObject message = MessageHelper.dateBaseError();
            response.getWriter().println(message);
            log.error(e.getMessage());
        }catch (Exception e){
            JSONObject message = MessageHelper.netWordError();
            response.getWriter().println(message);
            log.error(e.getMessage());
        }
    }
}